package com.hmall.trade.task;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.api.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.BatchingRabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderCheckTask {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private BatchingRabbitTemplate batchingRabbitTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    /***
     * 使用定时任务
     */
    @Scheduled(fixedRate = 60000)
    public void loadNoPayOrder(){
        //1、查询距离过期不足1分钟的订单
        List<Order> orders = loadNoPayOrderList();

        //2、批量发送延时消息到RabbitMQ
        orders.forEach(o->{
            batchingRabbitTemplate.convertAndSend("order.no_pay.delay.exchange", "no_pay", o.getId(), new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    Duration between = Duration.between(LocalDateTime.now(), o.getCreateTime().plusMinutes(30));
                    long millis = between.toMillis();
                    message.getMessageProperties().setDelayLong(millis);
                    return message;
                }
            },new CorrelationData(UUID.fastUUID().toString()));
        });

    }



    /***
     * 查询距离过期（30分钟）不足1分钟的订单    当前时间-（过期时间（分钟）-1分钟）
     * 10:02  10:03  10:04  10:05  10:06  10:07  10:08  10:09  10:10  10:11  10:12  10:13  10:14
     */
    public List<Order> loadNoPayOrderList(){
        List<Order> list = orderService.list(
                Wrappers.<Order>lambdaQuery()
                        //1、状态->未支付
                        .eq(Order::getStatus, 1)
                        //2、距离过期不足1分钟的订单
                        .lt(Order::getCreateTime, LocalDateTime.now().minusMinutes(29)));
        return list;
    }
}
